package com.cli.idempotent.service;

import com.cli.idempotent.constant.CommonConstants;
import com.cli.idempotent.constant.ResponseCode;
import com.cli.idempotent.exception.ServiceException;
import com.cli.idempotent.util.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;

/**
 * @author xiongmin
 * @version 0.0.1
 * @description Created by work on 2021/10/31 1:43 下午
 * @see
 */
@Service
@Slf4j
public class TokenServiceImpl implements TokenService {

    @Autowired
    private RedisUtils redisUtils;


    @Override
    public String createToken() {
        String str = UUID.randomUUID().toString();
        StringBuilder token = new StringBuilder();
        try {
            token.append(CommonConstants.REDIS_TOKEN_PREFIX).append(str);
            redisUtils.set(token.toString(), token.toString(), 10000L);
            boolean notEmpty = StringUtils.isNotEmpty(token.toString());
            if (notEmpty) {
                return token.toString();
            }
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
        }
        return null;
    }

    @Override
    public boolean checkToken(HttpServletRequest request) throws ServiceException {
        String token = request.getHeader(CommonConstants.REDIS_TOKEN_NAME);
        // header中不存在token
        if (StringUtils.isBlank(token)) {
            token = request.getParameter(CommonConstants.REDIS_TOKEN_NAME);
            // parameter中也不存在token
            if (StringUtils.isBlank(token)) {
                throw new ServiceException(ResponseCode.ILLEGAL_ARGUMENT, 100);
            }
        }

        if (!redisUtils.hasKey(token)) {
            throw new ServiceException(ResponseCode.REPETITIVE_OPERATION, 200);
        }

        long remove = redisUtils.del(token);
        if (remove == 0) {
            throw new ServiceException(ResponseCode.REPETITIVE_OPERATION, 200);
        }
        return true;
    }
}
